﻿using Microsoft.AspNetCore.Http;
using NLog.Fluent;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace AggregationGateway
{
    public class ResponseTimeMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger logger;
        public ResponseTimeMiddleware(RequestDelegate next, ILogger<ResponseTimeMiddleware> logger)
        {
            this.next = next;
            this.logger = logger;
        }

        public Task Invoke(HttpContext ctx)
        {
            var reqId = ctx.Connection.Id;
            Stopwatch watcher = new Stopwatch();
            watcher.Start();
            logger.LogInformation("ApiGetway Request begin.");
            logger.LogInformation("reqId={reqId}", reqId);
            //开始输出响应头,表示请求已经完成
            ctx.Response.OnStarting(() =>
            {
                watcher.Stop();
                logger.LogInformation("reqId={reqId},request was over,time={time}", reqId, watcher.ElapsedMilliseconds);
                return Task.CompletedTask;
            });

            next.Invoke(ctx);

            return Task.CompletedTask;
        }
    }
}
